// 写路由, 用户相关路由
const express = require("express")
const router = express.Router()
const multer = require('multer')
const path = require("path")
const upload = multer({ dest: path.join('client', 'temp-image') })
const fs = require("fs")
const { update,findId } = require("../model/blog")

/* 
  上传图片
*/
router.post("/upload", upload.single('img'), (req, res) => {
  console.log(req.file  );
  const { filename } = req.file
  console.log(req.body)
  let oldPath = req.file.destination + '/' + filename
  let newPath = req.file.destination + '/' + filename + req.file.originalname
  // 将接受后的文件进行重命名
  require('fs').renameSync(oldPath, newPath)
  const url = newPath
  console.log(url);
  res.send({
    "errno": 0, // 注意：值是数字，不能是字符串
    "data": {
      "url": `/${url}`, // 图片 src ，必须
      "alt": `${filename}`, // 图片描述文字，非必须
    }
  })
})

/* 
  删除图片
*/
router.post("/delete", (req, res) => {
  // 获取需要删除的文件地址
  const { del } = req.body
  del.forEach(ele => {
    const filePath = `./${ele}`; // 文件路径
    fs.unlinkSync(filePath)
  });
  res.send({
    code: 1,
    message: "已删除多余图片"
  });
})

/* 
  上传博客
*/
router.post("/add", async (req, res) => {
  const { id, blogData } = req.body
  const r = await update(id, blogData)
  res.send({
    code: 1,
    message: "发布成功"
  })
})

/* 
  获取博客
*/
router.post("/get",async (req,res)=>{
  const {id} = req.body
  const data = await findId(id)
  console.log(data);
  res.send({
    code: 1,
    data
  })
})


module.exports = router